package com.example.teaching_server.dto;

import com.example.teaching_server.entity.CourseRecording;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 课程录播数据传输对象
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "课程录播信息")
public class CourseRecordingDTO {

    @NotNull(message = "录播ID不能为空")
    @Schema(description = "录播唯一标识", example = "1")
    private Long id;

    @NotBlank(message = "缩略图不能为空")
    @Size(max = 500, message = "缩略图URL长度不能超过500个字符")
    @Schema(description = "课程缩略图URL", example = "https://example.com/thumbnail.jpg")
    private String thumbnailUrl;

    @NotBlank(message = "课程标题不能为空")
    @Size(max = 200, message = "课程标题长度不能超过200个字符")
    @Schema(description = "课程标题", example = "Java编程基础入门")
    private String title;

    @NotNull(message = "开始时间不能为空")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Schema(description = "课程开始时间", example = "2024-03-01 09:00:00")
    private LocalDateTime startTime;

    @NotNull(message = "结束时间不能为空")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Schema(description = "课程结束时间", example = "2024-03-01 10:30:00")
    private LocalDateTime endTime;

    @NotBlank(message = "班级名称不能为空")
    @Size(max = 50, message = "班级名称长度不能超过50个字符")
    @Schema(description = "所属班级", example = "计算机科学一班")
    private String className;

    @Size(max = 2000, message = "课程描述长度不能超过2000个字符")
    @Schema(description = "课程详细描述", example = "本课程介绍Java编程语言的基础知识和实践技巧")
    private String description;

    @NotBlank(message = "视频URL不能为空")
    @Size(max = 500, message = "视频URL长度不能超过500个字符")
    @Schema(description = "视频播放地址", example = "https://example.com/video.mp4")
    private String videoUrl;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Schema(description = "创建时间", example = "2024-03-01 08:00:00")
    private LocalDateTime createdAt;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Schema(description = "更新时间", example = "2024-03-01 08:05:00")
    private LocalDateTime updatedAt;

    /**
     * 从实体类转换为DTO（现代化版本）
     */
    public static CourseRecordingDTO fromEntity(CourseRecording entity) {
        if (entity == null) {
            return null;
        }

        return CourseRecordingDTO.builder()
                .id(entity.getId())
                .thumbnailUrl(entity.getThumbnailUrl())
                .title(entity.getTitle())
                .startTime(entity.getStartTime())
                .endTime(entity.getEndTime())
                .className(entity.getClassName())
                .description(entity.getDescription())
                .videoUrl(entity.getVideoUrl())
                .createdAt(entity.getCreatedAt())
                .updatedAt(entity.getUpdatedAt())
                .build();
    }

    /**
     * 兼容旧版本Service的辅助方法（保持向后兼容）
     */
    public static CourseRecordingDTO of(Long id, String thumbnailUrl, String title, String timeRange,
                                        String className, String description, String videoUrl) {
        // 解析时间范围字符串，如 "09:00-10:30"
        LocalDateTime[] times = parseTimeRange(timeRange);

        return CourseRecordingDTO.builder()
                .id(id)
                .thumbnailUrl(thumbnailUrl)
                .title(title)
                .startTime(times[0])
                .endTime(times[1])
                .className(className)
                .description(description)
                .videoUrl(videoUrl)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .build();
    }

    /**
     * 解析时间范围字符串
     */
    private static LocalDateTime[] parseTimeRange(String timeRange) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now;
        LocalDateTime endTime = now.plusHours(1);

        if (timeRange != null && timeRange.contains("-")) {
            String[] parts = timeRange.split("-");
            if (parts.length == 2) {
                try {
                    // 假设格式为 "HH:mm-HH:mm"
                    startTime = LocalDateTime.of(now.toLocalDate(),
                            java.time.LocalTime.parse(parts[0]));
                    endTime = LocalDateTime.of(now.toLocalDate(),
                            java.time.LocalTime.parse(parts[1]));
                } catch (Exception e) {
                    // 解析失败，使用默认值
                }
            }
        }
        return new LocalDateTime[]{startTime, endTime};
    }

    /**
     * 获取格式化时间段（用于前端显示）
     */
    @Schema(description = "格式化时间段", accessMode = Schema.AccessMode.READ_ONLY)
    public String getFormattedTimeRange() {
        if (startTime != null && endTime != null) {
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
            return startTime.format(timeFormatter) + "-" + endTime.format(timeFormatter);
        }
        return "";
    }

    /**
     * 获取课程时长（分钟）
     */
    @Schema(description = "课程时长（分钟）", accessMode = Schema.AccessMode.READ_ONLY)
    public Long getDurationMinutes() {
        if (startTime != null && endTime != null) {
            return java.time.Duration.between(startTime, endTime).toMinutes();
        }
        return 0L;
    }
}
